//
//  XYClassfySelectController.swift
//  XYReadBook
//
//  Created by fox on 2017/9/7.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit
 let Identifier = "ClassfySelectIdentifier"
/// 分类选择,例玄幻,奇幻,武侠
class XYClassfySelectController: XYViewController {

    var dataArr:[BookModel] = [] {
        didSet {
             self.tableView.reloadData()
        }
    }
   
    var headerView = XYClassfySelectHeaderView()
     var typeStr = "new"
     var major = ""
     var minor = ""
     var gender:String
     var name:String
    /// 顶部头部mdoel
    var headerModel:MajorGeneral
    init(name:String,gender:String,model:MajorGeneral) {
       self.name = name
       self.gender = gender
       self.headerModel = model
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var tableView:UITableView = {
        let tableView = UITableView.init(frame: CGRect.zero, style: .grouped)
        tableView.backgroundColor = UIColor.hm_color(withRed: 242, green: 242, blue: 242)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.register(XYClassfySelectCell.self, forCellReuseIdentifier:Identifier)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if HTTPManager.isnetWorkBool() == false {
            let errorView = XYErrorView.init(frame: self.view.bounds, errorType: .errorNotWork)
            view.addSubview(errorView)
            weak var weakSelf = self
            errorView.overrideLoadData = {
                XYLog(messsage: "重新加载网络数据")

                weakSelf?.loadData(major: (weakSelf?.name.urlEncode!)!, minor: "", type: "over")
            }
        }else {
            setupUI()
            loadData(major: name.urlEncode!, minor: "", type: "over")
        }


    }
    
    func setupUI() {
        navigationItem.title = name

        if gender == "female" || gender == "male" {
            headerView.titles = headerModel.mins
            headerView.delegate = self
            view.addSubview(headerView)
            headerView.backgroundColor = UIColor.white
        }
        view.addSubview(tableView)
        let item = UIBarButtonItem(title: "返回", style: .plain, target: self, action: nil)
        navigationItem.backBarButtonItem = item
        
    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
      
        var tabY = 0
        if gender == "female" || gender == "male" {
            
            var headerViewH = 44
            if headerModel.mins.count > 0 {
                headerViewH = 88
            }
            headerView.frame = CGRect.init(x: 0, y: 64, width: Int(ScreenWidth), height: headerViewH)
            tabY = Int(headerView.frame.maxY)
        }
    
        tableView.frame = CGRect.init(x: 0, y: CGFloat(tabY), width: ScreenWidth, height: ScreenHeight - headerView.height)
    }
    
    
    
   // http://api.zhuishushenqi.com/book/by-categories?limit=3&start=0&type=over&major=玄幻&minor=异界大陆
    func loadData(major:String,minor:String = "",type:String) {
        
        let urlStr = String.init(format: "book/by-categories?gender=%@&type=%@&major=%@&minor=%@&start=0&limit=20",gender,type,major,minor )
        
      let urlString = XYAPI.baseurlFormat(baseURL: BaseUrl.defult.rawValue, key: urlStr)
        weak var weakSelf = self
        HTTPManager.requestModel(url: urlString, method: .get, parameters: nil, iscaChe: true) { (resp:XYClassfySelectModel?, error ) in
            
            if let resp = resp {
               weakSelf?.setupUI()
                self.dataArr = resp.books
            }
            
        }
    }
}


extension XYClassfySelectController:XYClassfySelectHeaderViewDelega {
    /// 切换一级 类型 好评 热门.连载完结
    ///
    /// - Parameter sender: 切换一级 类型 好评 热门.连载完结
    func classfySelectType(sender:UIButton,headView:XYClassfySelectHeaderView) {
        //在这里直接请求
       
        switch sender.tag {
        case 0:
            // new
            typeStr = "new"
            break
        case 1:
            // hot
            typeStr = "hot"
            break
        case 2:
            typeStr = "reputation"
            break
        case 3:
            typeStr = "over"
            break
        default: break
        }
        
       
        
        loadData(major:name.urlEncode!,minor:minor.urlEncode!, type: typeStr.urlEncode!)
        
        
    }
    
    /// 切换二级分类
    ///
    /// - Parameter sender: 例如,玄幻大陆,异世大陆,穿越
    func classfySelectTitle(sender:UIButton,headView:XYClassfySelectHeaderView){
       
        if let str = sender.titleLabel?.text {
            if sender.tag == 0 {
                minor = ""
            }else {
                minor = str
            }

            
            loadData(major:name.urlEncode!,minor:minor.urlEncode!,type: typeStr.urlEncode!)
        }
    }
}

extension XYClassfySelectController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)as!XYClassfySelectCell
        cell.model = dataArr[indexPath.row]
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if dataArr.count == 0 {
            return
        }
        let bookID = dataArr[indexPath.row].id
        
        
        let vc = XYBookDetailsController.init(bookID: bookID,stateString:typeStr)
       
        navigationController?.pushViewController(vc, animated: true)
     
    }
}

